package com.nuanshui.heatedloan.task.quartz;

import static org.quartz.TriggerBuilder.newTrigger;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nuanshui.framework.utils.LogUtil;
import com.nuanshui.heatedloan.task.dal.mapper.TaskJobFailMapper;
import com.nuanshui.heatedloan.task.facade.QuartzTaskManager;
import com.nuanshui.heatedloan.task.facade.bean.JobParams;
import com.nuanshui.heatedloan.task.facade.bean.JobProvider;
import com.nuanshui.heatedloan.task.facade.model.TaskJobFail;
import com.nuanshui.heatedloan.task.job.QuartzJobBean;
import com.nuanshui.heatedloan.task.util.CommonUtil;

/**
 * 定时任务管理service
 * @param 
 * @author guohao
 * @date 2017年2月13日 上午10:04:38
 * @since $
 */
@Service("quartzTaskManager")
public class QuartzTaskManagerImpl implements QuartzTaskManager,InitializingBean {

	@Autowired
	private Scheduler scheduler;
	
	@Autowired
	private TaskJobFailMapper taskJobFailMapper;
	@Autowired
	private static final Logger logger = LoggerFactory.getLogger("TASK_LOG");
	
	/**
	 * 增加一个任务
	 * @param @param jobProvider
	 * @param @param date
	 * @author guohao
	 * @date 2017年2月13日 上午10:04:52
	 * @since $
	 *  
	 * @see com.nuanshui.heatedloan.task.facade.QuartzTaskManager#addJob(com.nuanshui.heatedloan.task.facade.bean.JobProvider, java.util.Date)
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void addJob(JobProvider jobProvider, Date date) {
		try {
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			LogUtil.info(logger, "date :" + sf.format(date));
			Class clazz =QuartzJobBean.class;//根据任务类型，获取对应的处理类
			//创建一个触发器
			String bizKey = jobProvider.getParams().getBizKey();
			JobDetail exeJob = JobBuilder.newJob(clazz).withIdentity(jobProvider.getJobName()+bizKey,jobProvider.getJobGroup()).build();
			JobDataMap jobDataMap =  exeJob.getJobDataMap();
			JobParams jobParams = jobProvider.getParams();
			jobParams.setJobCode(CommonUtil.generateJobCode(jobParams));
			jobDataMap.put("job_params",jobProvider.getParams());
			jobParams.setJobName(jobProvider.getJobName());
			jobParams.setJobGroup(jobProvider.getJobGroup());
			SimpleTrigger trigger = (SimpleTrigger) newTrigger().withIdentity(jobProvider.getJobName()+"_"+bizKey,jobProvider.getJobGroup()).startAt(date).build();			
			//根据触发器和job，安排任务
			scheduler.scheduleJob(exeJob, trigger);
			LogUtil.info(logger, "创建成功~~~~本次创建的任务："+jobProvider.getJobGroup()+"---任务组中的----"+jobProvider.getJobName()+"---------------------");
		} catch (SchedulerException e) {
			e.printStackTrace();
		} 
		
	}
	
	/**
	 * 停止一个任务
	 * @param @param jobProvider
	 * @author guohao
	 * @date 2017年2月13日 上午10:05:10
	 * @since $
	 *  
	 * @see com.nuanshui.heatedloan.task.facade.QuartzTaskManager#stopJob(com.nuanshui.heatedloan.task.facade.bean.JobProvider)
	 *
	 */
	@Override
	public void stopJob(JobProvider jobProvider) {
		JobKey jobKey = new JobKey(jobProvider.getJobName(),jobProvider.getJobGroup());
		try {
			scheduler.deleteJob(jobKey);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 延迟一个任务
	 * @param @param jobProvider
	 * @param @param date 延迟的时间
	 * @author guohao
	 * @date 2017年2月13日 上午10:05:20
	 * @since $
	 *  
	 * @see com.nuanshui.heatedloan.task.facade.QuartzTaskManager#delayJob(com.nuanshui.heatedloan.task.facade.bean.JobProvider, java.util.Date)
	 *
	 */
	@Override
	public void delayJob(JobProvider jobProvider,Date date) {
		try {
		   
			LogUtil.info(logger, jobProvider.getJobName()+"a");
			
			TriggerKey triggerKey = TriggerKey.triggerKey(jobProvider.getJobName(), jobProvider.getJobGroup());
			LogUtil.info(logger, scheduler.checkExists(triggerKey)+"");
			SimpleTrigger trigger = (SimpleTrigger) newTrigger().withIdentity(jobProvider.getJobName(),jobProvider.getJobGroup()).startAt(date).build();
			scheduler.rescheduleJob(triggerKey, trigger);
		} catch (SchedulerException e) {		
			e.printStackTrace();	
		}
	}



	/**
	 * 暂停一个任务
	 * @param @param jobProvider
	 * @author guohao
	 * @date 2017年2月13日 上午10:05:34
	 * @since $
	 *  
	 * @see com.nuanshui.heatedloan.task.facade.QuartzTaskManager#pauseJob(com.nuanshui.heatedloan.task.facade.bean.JobProvider)
	 *
	 */
	@Override
	public void pauseJob(JobProvider jobProvider){
		JobKey jobKey = new JobKey(jobProvider.getJobName(),jobProvider.getJobGroup());
		try {
			scheduler.pauseJob(jobKey);
			LogUtil.info(logger, "暂停成功~~~~本次暂停的任务："+jobKey.getGroup()+"---任务组中的----"+jobKey.getName()+"---------------------");
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 恢复一个任务
	 * @param @param jobProvider
	 * @author guohao
	 * @date 2017年2月13日 上午10:05:49
	 * @since $
	 *  
	 * @see com.nuanshui.heatedloan.task.facade.QuartzTaskManager#resumeJob(com.nuanshui.heatedloan.task.facade.bean.JobProvider)
	 *
	 */
	@Override
	public void resumeJob(JobProvider jobProvider){
		JobKey jobKey = new JobKey(jobProvider.getJobName(),jobProvider.getJobGroup());
		try {
			
			scheduler.resumeJob(jobKey);
			LogUtil.info(logger, "继续任务成功~~本次继续的任务："+jobKey.getGroup()+"---任务组中的----"+jobKey.getName()+"---------------------");
			
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}


	@Override
	public void afterPropertiesSet() throws Exception {
		JobProvider jobProvider =  new JobProvider("test1", "test");
		jobProvider.addParams("test", "test");
		Calendar calendar = Calendar.getInstance();
		//calendar.add(Calendar.MILLISECOND, 30);
		//this.addJob(jobProvider,calendar.getTime());
		
		TaskJobFail taskJobFail = new TaskJobFail();
		taskJobFail.setFailTime(new Date());
		taskJobFail.setJobCode("aaa");
		taskJobFail.setNum(1);
		taskJobFail.setJobGroup("Test");
		taskJobFail.setJobName("Test");
		
		taskJobFail.setJobParams("aaa");
		
		//this.taskJobFailMapper.save(taskJobFail);
	}	
	
	
	
}
